/*
 * Copyright 2009 Colin Prinn
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package net.recursv.motific.at.command;

import net.recursv.motific.utils.WrappedException;

import java.util.Hashtable;

/**
 * Created by: recursv
 * Date: 13/08/2009
 * Time: 3:45:59 PM
 */
public final class AtCommandManager {
    private final static Hashtable _map = new Hashtable();

    /**
     * Populates the map with framework commands.
     */
    static {
        try {
            _map.put(AssertExitCommand.IDENTIFIER, Class.forName("net.recursv.motific.at.command.AssertExitCommand"));
            _map.put(AssertSceneContainsCommand.IDENTIFIER, Class.forName("net.recursv.motific.at.command.AssertSceneContainsCommand"));
            _map.put(AssertStartAppCommand.IDENTIFIER, Class.forName("net.recursv.motific.at.command.AssertStartAppCommand"));
            _map.put(EnterTextCommand.IDENTIFIER, Class.forName("net.recursv.motific.at.command.EnterTextCommand"));
            _map.put(ExitAppCommand.IDENTIFIER, Class.forName("net.recursv.motific.at.command.ExitAppCommand"));
            _map.put(KeyPressCommand.IDENTIFIER, Class.forName("net.recursv.motific.at.command.KeyPressCommand"));
            _map.put(StartAppCommand.IDENTIFIER, Class.forName("net.recursv.motific.at.command.StartAppCommand"));
        } catch (Throwable e) {
            throw new WrappedException(e);
        }
    }

    private AtCommandManager() {
    }

    /**
     * Add an at command to the map
     *
     * @param identifier the identifier used in the at script
     * @param command    the at command class to attach to the map
     */
    public static void addCommand(String identifier, Class command) {
        _map.put(identifier, command);
    }

    /**
     * Instantiates a new instance of the requested at command
     *
     * @param identifier the identifier used in the at script
     * @return a new at command instance
     */
    public static AtCommand getCommand(String identifier) {

        if (_map.containsKey(identifier)) {
            try {
                return (AtCommand) ((Class) _map.get(identifier)).newInstance();
            } catch (Throwable e) {
                throw new WrappedException(e);
            }
        } else
            throw new RuntimeException("Unknown command: " + identifier);
    }
}
